package com.zygh.lz.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zygh.lz.constant.SystemCon;
import com.zygh.lz.dao.*;
import com.zygh.lz.entity.*;
import com.zygh.lz.entity.remould.Patrol;
import com.zygh.lz.entity.remould.Xareas;
import com.zygh.lz.entity.vo.CoordinateData;
import com.zygh.lz.entity.vo.Patrolrecords;
import com.zygh.lz.service.PatrolrecordService;
import com.zygh.lz.stapprove.DouglasPeuckerUtil;
import com.zygh.lz.stapprove.ResultUtil;
import com.zygh.lz.util.DataTime;
import com.zygh.lz.util.DistanceUtil;
import com.zygh.lz.util.SignTime;
import com.zygh.lz.util.TreeUtil;
import com.zygh.lz.vo.ResultBean;
import com.zygh.lz.vo.ResultBeans;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.geom.Point2D;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static com.zygh.lz.util.SignTime.*;

@Slf4j
@Service
public class PatrolrecordServiceImpl implements PatrolrecordService {

    @Resource
    private PatrolrecordMapper patrolrecordMapper;
    @Resource
    private StaffMapper staffMapper;
    @Resource
    private GpsMapper gpsMapper;
    @Resource
    private ProblemMapper problemMapper;
    @Resource
    private XareaMapper xareaMapper;
    @Resource
    private XlevelserviceMapper xlevelserviceMapper;
    @Resource
    private SectionMapper sectionMapper;
    @Resource
    private SignMapper signMapper;
    @Resource
    private SptypeMapper sptypeMapper;
    @Resource
    private GatecardMapper gatecardMapper;
    @Resource
    private LocationMapper locationMapper;
    @Resource
    private EquipageMapper equipageMapper;

    @Resource
    private DutyModelMapper dutyModelMapper;

    @Resource
    private TreeUtil treeUtil;

    //设置日期格式
    private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    /**
     * 新增巡查记录
     *
     * @param patrolrecord 入参
     * @return ResultBeans
     */
    @Override
    public ResultBeans addPatrolrecord(Patrolrecord patrolrecord) {
        if (patrolrecord.getSysStaffId() != null) {
            Sign sign = signMapper.findlastByid(patrolrecord.getSysStaffId());
            if (sign != null) {
                String assignmentname = sign.getAssignmentname();
                String[] split = assignmentname.split("-");
                patrolrecord.setRoadName(split[split.length - 1]);
            } else {
                patrolrecord.setRoadName(DateUtil.date().toString());
            }
        }
        patrolrecord.setPatrolRecordBegintime(DateUtil.date());
        int i = patrolrecordMapper.insertSelective(patrolrecord);
        if (i > 0) {
            //上线
            Staff staff = new Staff();
            staff.setSysStaffId(patrolrecord.getSysStaffId());
            staff.setStaffOnline("1");
            staffMapper.updateByPrimaryKeySelective(staff);
            //返回巡查记录id
            //return ResultUtil.setOK("success", patrolrecord.getSysPatrolRecordId());
            return ResultUtil.resultBeansSuccess(patrolrecord.getSysPatrolRecordId());
        }
        //return ResultUtil.setError(SystemCon.RERROR1, "error", null);
        return ResultUtil.resultBeansError(null);
    }

    @Override
    public int addPatrolrecords(Patrolrecord patrolrecord) {
        if (patrolrecord.getSysStaffId() != null) {
            Sign sign = signMapper.findlastByid(patrolrecord.getSysStaffId());
            if (sign != null) {
                String assignmentname = sign.getAssignmentname();
                String[] split = assignmentname.split("-");
                patrolrecord.setRoadName(split[split.length - 1]);
            } else {
                patrolrecord.setRoadName(DateUtil.date().toString());
            }
        }
        patrolrecord.setPatrolRecordBegintime(DateUtil.date());
        int i = patrolrecordMapper.insertSelective(patrolrecord);
        if (i > 0) {
            //上线
            Staff staff = new Staff();
            staff.setSysStaffId(patrolrecord.getSysStaffId());
            staff.setStaffOnline("1");
            staffMapper.updateByPrimaryKeySelective(staff);
            //返回巡查记录id
            return patrolrecord.getSysPatrolRecordId();
        }
        return 0;
    }


    /**
     * 修改巡查记录
     *
     * @param patrolrecord
     * @return
     */
    @Override
    public ResultBeans updatePatrolrecord(Patrolrecord patrolrecord) {
        //获取修改id
        Integer sysPatrolRecordId = patrolrecord.getSysPatrolRecordId();
        Patrolrecord patrolrecord1 = patrolrecordMapper.selectByPrimaryKey(sysPatrolRecordId);
        Sign sign = signMapper.findlastByid(patrolrecord1.getSysStaffId());
        if (sign != null) {
            if (sign.getSignouttime() != null) {
                // Convert.toDate(d)
                patrolrecord.setPatrolRecordEndtime(DateUtil.parseDateTime(DateUtil.now()));
            }
        }

        if (patrolrecord.getPatrolRecordGps() != null) {
            //修改app穿过来的gps坐标格式
            String patrolRecordGps = DouglasPeuckerUtil.replace(patrolrecord.getPatrolRecordGps());
            if (patrolrecord1.getPatrolRecordGps() != null && !patrolrecord1.getPatrolRecordGps().equals("")) {
                patrolrecord.setPatrolRecordGps(patrolrecord1.getPatrolRecordGps() + "," + patrolRecordGps);
            } else {
                patrolrecord.setPatrolRecordGps(patrolRecordGps);
            }
        }

        //return ResultUtil.execOp(patrolrecordMapper.updateByPrimaryKeySelective(patrolrecord), "修改");
        return ResultUtil.resultBeansexecOp(patrolrecordMapper.updateByPrimaryKeySelective(patrolrecord), "修改");
    }

    /**
     * 根据id删除巡查记录
     *
     * @param id
     * @return
     */
    @Override
    public ResultBean delPatrolrecord(Integer id) {
        gpsMapper.deleteByPatrolId(id);
        return ResultUtil.execOp(patrolrecordMapper.deleteByPrimaryKey(id), "删除");
    }

    /**
     * 根据道路类型、部门查询所有巡查信息(分层查询)
     * 管理员看所有,大队长看本大队，中队长看中队，警员看个人
     *
     * @param staffid
     * @return
     */
    @Override
    public ResultBean selectByRoadtype(Integer staffid, String beginTime, String endTime, String staffnum,
                                       Integer sectionPid, Integer pageNo, Integer pageSize) {
        PageHelper.startPage(pageNo, pageSize);
        //登陆人信息
        Staff staff = staffMapper.selectByPrimaryKey(staffid);
        if (staff == null) {
            return ResultUtil.setError(SystemCon.RERROR1, "请传入登录人主键", null);
        }
        //提取个人信息中得所属大队
        Integer sysSectionId = staff.getSysSectionId();
        //提取个人信息中的职务大队长/中队长
        String staffpost = staff.getStaffPost();
        Section section = sectionMapper.selectByPrimaryKey(staff.getSysSectionId());

        if (staffpost != null) {
            if ("大队长".equals(staffpost) || "副大队长".equals(staffpost) || "指导员".equals(staffpost)) {
                //本大队
                PageHelper.startPage(pageNo, pageSize);
                List<Patrolrecords> patrolrecordList = patrolrecordMapper.selectByRoadtype(null, beginTime, endTime, section.getSectionPid(), staffnum);
                this.addInfo(patrolrecordList);
                PageInfo<Patrolrecords> patrolrecords2s = new PageInfo<>(patrolrecordList);
                return ResultUtil.setOK("success", patrolrecords2s);

            } else if ("中队长".equals(staffpost) || "2245".equals(staff.getStaffNum()) || "007828".equals(staff.getStaffNum())) {
                //本中队巡查记录
                PageHelper.startPage(pageNo, pageSize);
                List<Patrolrecords> patrolrecords2 = patrolrecordMapper.selectByRoadtype(sysSectionId, beginTime, endTime, null, staffnum);
                this.addInfo(patrolrecords2);
                PageInfo<Patrolrecords> patrolrecords2s = new PageInfo<>(patrolrecords2);
                return ResultUtil.setOK("success", patrolrecords2s);
            } else if ("管理员".equals(staffpost)) {
                System.out.println("《《《《《《《《《《《《《《《《管理员");
                PageHelper.startPage(pageNo, pageSize);
                List<Patrolrecords> patrolrecords2 = patrolrecordMapper.selectByRoadtype(null, beginTime, endTime, null, staffnum);
                if (patrolrecords2.size() > 0) {
                    this.addInfo(patrolrecords2);
                    PageInfo<Patrolrecords> patrolrecords2s = new PageInfo<>(patrolrecords2);
                    return ResultUtil.setOK("success", patrolrecords2s);
                }

                return ResultUtil.setError(SystemCon.RERROR1, "error", null);
            } else {
                return ResultUtil.setError(SystemCon.RERROR1, "error", null);
            }
        } else { //如果为普通民警只能看自己的巡查轨迹
            System.out.println("《《《《《《《《《《《《《《《《普通人员");
            PageHelper.startPage(pageNo, pageSize);
            List<Patrolrecords> patrolrecords2 = patrolrecordMapper.selectBysysStaffId(staffid, beginTime, endTime);
            this.addInfo(patrolrecords2);
            PageInfo<Patrolrecords> patrolrecords2s = new PageInfo<>(patrolrecords2);
            return ResultUtil.setOK("success", patrolrecords2s);
        }
    }


    private void addInfo(List<Patrolrecords> patrolrecordList) {
        if (patrolrecordList.size() > 0) {
            patrolrecordList.forEach(record -> {
                //新增问题列表
                //
                Integer patrolrecordId = record.getSysPatrolRecordId();
                List<Problem> problemList = problemMapper.selectProblemByRecord(patrolrecordId);
                record.setProblemList(problemList);
            });
        }

    }


    /**
     * @param startTime
     * @param endTime
     * @return
     * @throws Exception
     */

    @Override
    public ResultBean countPatrolrecord(String startTime, String endTime) throws Exception {
        //处理时间
        Date startDate = simpleDateFormat.parse(startTime);
        Date endDate = simpleDateFormat.parse(endTime);

        List<Map> list = new ArrayList<>();

        int one1 = patrolrecordMapper.countPatrolrecord("一大队", "主干道", startDate, endDate);
        int one2 = patrolrecordMapper.countPatrolrecord("一大队", "拥堵路段", startDate, endDate);
        int one3 = patrolrecordMapper.countPatrolrecord("一大队", "施工路段", startDate, endDate);
        int one4 = one1 + one2 + one3;
        Map<String, Object> map1 = new HashMap<>();
        map1.put("zgd", one1);
        map1.put("ydld", one2);
        map1.put("sgld", one3);
        map1.put("sum", one4);
        Map<String, Object> map11 = new HashMap<>();
        map11.put("sectionName", "一大队");
        map11.put("staffHierarchay", map1);
        list.add(map11);

        int two1 = patrolrecordMapper.countPatrolrecord("二大队", "主干道", startDate, endDate);
        int two2 = patrolrecordMapper.countPatrolrecord("二大队", "拥堵路段", startDate, endDate);
        int two3 = patrolrecordMapper.countPatrolrecord("二大队", "施工路段", startDate, endDate);
        int two4 = two1 + two2 + two3;
        Map<String, Object> map2 = new HashMap<>();
        map2.put("zgd", two1);
        map2.put("ydld", two2);
        map2.put("sgld", two3);
        map2.put("sum", two4);
        Map<String, Object> map22 = new HashMap<>();
        map22.put("sectionName", "二大队");
        map22.put("staffHierarchay", map2);
        list.add(map22);

        int three1 = patrolrecordMapper.countPatrolrecord("三大队", "主干道", startDate, endDate);
        int three2 = patrolrecordMapper.countPatrolrecord("三大队", "拥堵路段", startDate, endDate);
        int three3 = patrolrecordMapper.countPatrolrecord("三大队", "施工路段", startDate, endDate);
        int three4 = three1 + three2 + three3;
        Map<String, Object> map3 = new HashMap<>();
        map3.put("zgd", three1);
        map3.put("ydld", three2);
        map3.put("sgld", three3);
        map3.put("sum", three4);
        Map<String, Object> map33 = new HashMap<>();
        map33.put("sectionName", "三大队");
        map33.put("staffHierarchay", map3);
        list.add(map33);

        int four1 = patrolrecordMapper.countPatrolrecord("四大队", "主干道", startDate, endDate);
        int four2 = patrolrecordMapper.countPatrolrecord("四大队", "拥堵路段", startDate, endDate);
        int four3 = patrolrecordMapper.countPatrolrecord("四大队", "施工路段", startDate, endDate);
        int four4 = four1 + four2 + four3;
        Map<String, Object> map4 = new HashMap<>();
        map4.put("zgd", four1);
        map4.put("ydld", four2);
        map4.put("sgld", four3);
        map4.put("sum", four4);
        Map<String, Object> map44 = new HashMap<>();
        map44.put("sectionName", "四大队");
        map44.put("staffHierarchay", map4);
        list.add(map44);

        int five1 = patrolrecordMapper.countPatrolrecord("五大队", "主干道", startDate, endDate);
        int five2 = patrolrecordMapper.countPatrolrecord("五大队", "拥堵路段", startDate, endDate);
        int five3 = patrolrecordMapper.countPatrolrecord("五大队", "施工路段", startDate, endDate);
        int five4 = five1 + five2 + five3;
        Map<String, Object> map5 = new HashMap<>();
        map5.put("zgd", five1);
        map5.put("ydld", five2);
        map5.put("sgld", five3);
        map5.put("sum", five4);
        Map<String, Object> map55 = new HashMap<>();
        map55.put("sectionName", "五大队");
        map55.put("staffHierarchay", map5);
        list.add(map55);

        int sex1 = patrolrecordMapper.countPatrolrecord("六大队", "主干道", startDate, endDate);
        int sex2 = patrolrecordMapper.countPatrolrecord("六大队", "拥堵路段", startDate, endDate);
        int sex3 = patrolrecordMapper.countPatrolrecord("六大队", "施工路段", startDate, endDate);
        int sex4 = sex1 + sex2 + sex3;
        Map<String, Object> map6 = new HashMap<>();
        map6.put("zgd", sex1);
        map6.put("ydld", sex2);
        map6.put("sgld", sex3);
        map6.put("sum", sex4);
        Map<String, Object> map66 = new HashMap<>();
        map66.put("sectionName", "六大队");
        map66.put("staffHierarchay", map6);
        list.add(map66);

        return ResultUtil.setOK("success", list);
    }

    /**
     * 查询所有巡查记录
     *
     * @return
     */
    @Override
    public ResultBean selectAllPatrolrecord() {
        List<Patrolrecord> patrolrecords = patrolrecordMapper.selectAllPatrolrecord();
        if (patrolrecords.size() > 0) {
            return ResultUtil.setOK("success", patrolrecords);
        }
        return ResultUtil.setError(SystemCon.RERROR1, "error", null);
    }

    /**
     * 查询所有巡查记录的视频
     *
     * @return
     */
    @Override
    public ResultBean selectVideo() {
        List<Patrolrecord> patrolrecords = patrolrecordMapper.selectVideo();
        if (patrolrecords.size() > 0) {
            List<Patrolrecord> list = new ArrayList<>();
            for (int i = 0; i < patrolrecords.size(); i++) {
                String[] strArray = null;
                String patrolRecordVideo = patrolrecords.get(i).getPatrolRecordVideo();
                //切割
                strArray = patrolRecordVideo.split("\\,");
                if (strArray.length > 0) {
                    for (int j = 0; j < strArray.length; j++) {
                        Patrolrecord patrolrecord = new Patrolrecord();
                        //拷贝
                        BeanUtils.copyProperties(patrolrecords.get(i), patrolrecord);
                        patrolrecord.setPatrolRecordVideo(strArray[j]);
                        list.add(patrolrecord);
                    }

                }
            }
            return ResultUtil.setOK("success", list);
        }
        return ResultUtil.setError(SystemCon.RERROR1, "error", null);
    }

    /**
     * 根据开始时间，结束时间、道路名称查询巡查记录
     *
     * @return
     */
    @Override
    public ResultBean selectDim(String roadName, String beginTime, String endTime) {
        List<Object> patrolrecords = patrolrecordMapper.selectDim(roadName, beginTime, endTime);
        if (patrolrecords.size() > 0) {
            return ResultUtil.setOK("success", patrolrecords);
        }
        return ResultUtil.setError(SystemCon.RERROR1, "error", null);
    }

    /**
     * 根据时间查询个人巡查记录
     *
     * @param SysStaffId
     * @param beginTime
     * @param endTime
     * @return
     */
    @Override
    public ResultBean selectByStaff(Integer SysStaffId, String beginTime, String endTime) {
        List<Map<String, Object>> patrolrecordList = patrolrecordMapper.selectByStaff(SysStaffId, beginTime, endTime);
        Map<String, Object> mape = new HashMap<>();
        List<Gps> gpsList1 = null;
        List<Problem> problemList = null;
        if (patrolrecordList.size() > 0) {
            for (int i = 0; i < patrolrecordList.size(); i++) {
                Integer problemid = (Integer) patrolrecordList.get(i).get("sys_patrol_record_id");
                if (SysStaffId != null && problemid != null) {
                    gpsList1 = gpsMapper.selectGpsByRecord(SysStaffId, problemid);
                }
                if (gpsList1.size() != 0) {
                    patrolrecordList.get(i).put("gpsList", gpsList1);
                    if (problemMapper.selectProblemByRecord(problemid) != null) {
                        problemList = problemMapper.selectProblemByRecord(problemid);
                        for (int j = 0; j < problemList.size(); j++) {
                            mape.put("problemList", problemList);
                        }
                    }
                } else {
                    continue;
                }
                patrolrecordList.get(i).put("problemList", problemList);

            }
            if (patrolrecordList.size() > 0 || patrolrecordList.size() == 0) {
                return ResultUtil.setOK("success", patrolrecordList);
            }

        }
        return ResultUtil.setError(SystemCon.RERROR1, "error", null);
    }

    @Override
    public ResultBean selectByStaffapp(Integer SysStaffId, String beginTime, String endTime) {
        List<Map<String, Object>> patrolrecordList = patrolrecordMapper.selectByStaff(SysStaffId, beginTime, endTime);
        //String arr[] = new String[20];
        if (patrolrecordList.size() > 0) {
            for (int i = 0; i < patrolrecordList.size(); i++) {
                Map<String, Object> map = patrolrecordList.get(i);
                Integer problemid = (Integer) map.get("sys_patrol_record_id");
                if (problemMapper.selectProblemByRecord(problemid) != null) {
                    List<Problem> problemList = problemMapper.selectProblemByRecord(problemid);
                    Map<String, Object> maps = new HashMap<>();
                    for (int c = 0; c < problemList.size(); c++) {
                        maps.put("problemList", problemList);
                    }
                }
            }
            if (patrolrecordList.size() > 0 || patrolrecordList.size() == 0) {
                return ResultUtil.setOK("success", patrolrecordList);
            }
        }
        return ResultUtil.setError(SystemCon.RERROR1, "error", null);
    }

    /**
     * 查询各个大队的巡查记录个数
     *
     * @param startDate
     * @param endDate
     * @return
     */
    @Override
    public ResultBean selectRecordNum(String startDate, String endDate) {
        List<Patrolrecord> patrolrecords = patrolrecordMapper.selectRecordNum(startDate, endDate);
        if (patrolrecords.size() > 0) {
            return ResultUtil.setOK("success", patrolrecords);
        }
        return ResultUtil.setError(SystemCon.RERROR1, "error", null);
    }

    /**
     * 根据登录用户负责道路列表
     *
     * @param staffId
     * @return
     */
    @Override
    public ResultBean selectByStaffId(Integer staffId) {
        Staff staff = staffMapper.selectInfoByid(staffId);
        List<Object> list = null;
        if (staff.getStaffHierarchy() != null) {
            if (staff.getStaffHierarchy().equals("一级路长")) {
                list = patrolrecordMapper.selectByStaffId(staffId);
            } else if (staff.getStaffHierarchy().equals("二级路长")) {
                list = patrolrecordMapper.selectBytwostaffId(staffId);
            } else {
                return ResultUtil.setError(SystemCon.RERROR1, "error", null);
            }
        }
        if (list != null) {
            if (list.size() > 0 || list.size() == 0) {
                return ResultUtil.setOK("success", list);
            }
        }
        return ResultUtil.setError(SystemCon.RERROR1, "error", null);
    }

    /**
     * 批量删除
     *
     * @param array
     * @return
     */
    @Override
    public ResultBean delectPatrolrecordById(int[] array) {
        return ResultUtil.execOp(patrolrecordMapper.delectPatrolrecordById(array), "批量删除");
    }

    /**
     * 根据id查询该人的巡查记录
     *
     * @param id
     * @return
     */
    @Override
    public ResultBeans selectAllPatrolrecordById(Integer id, String time, Integer current, Integer size) {
        PageHelper.startPage(current, size);
        String startTime;
        String endTime;
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(time)) {
            startTime = time + " 00:00:00";
            endTime = time + " 23:59:59";
        } else {
            startTime = DataTime.getStartDate();
            endTime = DataTime.getEndDate();
        }
        List<Map> patrolrecords = patrolrecordMapper.selectAllPatrolrecordById(id, startTime, endTime);
        PageInfo<Map> pageInfo = new PageInfo<>(patrolrecords);
        return ResultUtil.resultBeansSuccess(pageInfo);
    }

    @Override
    public ResultBeans selectAllGPSById(Integer staffId, Integer patrolrecordId) {
        List<Gps> gpsList = gpsMapper.selectGpsByRecord(staffId, patrolrecordId);
        String allGps = gpsList.stream().map(x -> x.getCoordinate()).collect(Collectors.joining(","));
        if (StringUtils.isEmpty(allGps)) {
            return ResultUtil.resultBeansSuccess(allGps);
        }
        return ResultUtil.resultBeansSuccess(allGps);
    }

    @Override
    public String selectTrackById(Integer staffId, Integer patrolrecordId) {
        List<Gps> gpsList = gpsMapper.selectGpsByRecord(staffId, patrolrecordId);
        String allGps = gpsList.stream().map(x -> x.getCoordinate()).collect(Collectors.joining(","));
        return allGps;
    }

    @Override
    public List<Map> selectTracksById(Integer patrolrecordId) {
        List<Map> gpsList = gpsMapper.selectGpsByRecordes(patrolrecordId);
        return gpsList;
    }


    @Override
    public ResultBean selectGPSById(Integer staffId, String startTime, String endTime) {
        //一周的时间
        List<Map> patrolrecordByDay = patrolrecordMapper.findPatrolrecordByDay(staffId, startTime, endTime);
        for (Map map : patrolrecordByDay) {
            //巡查记录
            List<Map> patrolrecordInfoById = patrolrecordMapper.findPatrolrecordInfoById(staffId, map.get("patrolRecordBegintime").toString());
            for (Map patrol : patrolrecordInfoById) {
                String signnum = patrol.get("signnum").toString();
                Integer patrolrecordId = Integer.valueOf(patrol.get("sysPatrolRecordId").toString());
                double mileage = gpsMapper.selectmileageByGps(patrolrecordId);
                //获取岗位
                List<Map> signByNum = signMapper.findSignByNum(signnum);
                if (signByNum.size() > 0) {
                    patrol.put("name", signByNum.get(0).get("staffname"));
                    patrol.put("signinfo", signByNum);
                }
                patrol.put("mileage", mileage);
            }
            map.put("details", patrolrecordInfoById);
        }
        return ResultUtil.setOK("success", patrolrecordByDay);
    }

    //抽稀算法
    @Override
    public String vacuateGPS(String allGps) {
        //坐标进行抽稀
        if (allGps.split(",").length < 3) {
            return allGps;
        }
        List<CoordinateData> coordinateData = convertToList(allGps);
        List<CoordinateData> coordinateData1 = DouglasPeuckerUtil.DouglasPeucker(coordinateData, 10);
        String collect = coordinateData1.stream().map(c -> c.getLatitude() + "," + c.getLongitude()).collect(Collectors.joining(","));

        return collect;
    }

    //抽稀算法
    @Override
    public String vacuatesGPS(List<CoordinateData> allGps) {
        //坐标进行抽稀
        List<CoordinateData> coordinateData1 = DouglasPeuckerUtil.DouglasPeucker(allGps, 10);
        String collect = coordinateData1.stream().map(c -> c.getLatitude() + "," + c.getLongitude()).collect(Collectors.joining(","));
        return collect;
    }

    //数据库里查询的GPS坐标转List
    public static List<CoordinateData> convertToList(String allGps) {
        List<CoordinateData> points = new ArrayList<>();
        CoordinateData coordinateData;
        String[] split = allGps.split(",");

        for (int i = 0; i < split.length; i++) {
            if (i % 2 == 0) {
                coordinateData = new CoordinateData();
                coordinateData.setLatitude(Double.valueOf(split[i]));
                coordinateData.setLongitude(Double.valueOf(split[i + 1]));
                points.add(coordinateData);
            }
        }
        return points;
    }

    private List<Staff> getChild(Integer id, List<Staff> rootMenu) throws NullPointerException {//int id  id 是指当前菜单id，rootMenu是指要查找的列表
        List<Staff> childList = new ArrayList<>();
        Iterator iterList = rootMenu.iterator();
        while (iterList.hasNext()) {
            Staff treemenu = (Staff) iterList.next();
            // 遍历所有节点，将父菜单id与传过来的id比较
            if (treemenu.getStafffPid() != 0) {
                if (treemenu.getStafffPid().equals(id)) {
                    childList.add(treemenu);
                }
            }
        }
        // 把子菜单的子菜单再循环一遍
        /*for (Treemenu treemenu : childList) {*/
        Iterator iterList2 = childList.iterator();
        while (iterList2.hasNext()) {
            Staff treemenu = (Staff) iterList2.next();
            treemenu.setStaffList(getChild(treemenu.getSysStaffId(), rootMenu));
        } // 递归退出条件
        if (childList.size() == 0) {
            return null;
        }
        return childList;
    }


    /**
     * 计算在线率
     *
     * @param onLineSign     在线民警
     * @param policeStrength 应在线民警
     * @return 在线率
     */
    public String signIntoRate(int onLineSign, int policeStrength) {
        // 创建一个数值格式化对象
        NumberFormat numberFormat = NumberFormat.getInstance();
        // 设置精确到小数点后2位
        numberFormat.setMaximumFractionDigits(2);
        String onlineRate = null;
        if (onLineSign == 0) {
            onlineRate = "0";
        } else if (onLineSign > policeStrength) {
            onlineRate = "100";
        } else {
            onlineRate = numberFormat.format((float) onLineSign / (float) policeStrength * 100);
        }
        return onlineRate;
    }

    private String police(int onLineSign) {
        // 创建一个数值格式化对象
        NumberFormat numberFormat = NumberFormat.getInstance();
        // 设置精确到小数点后2位
        numberFormat.setMaximumFractionDigits(0);
        String onlineRate = numberFormat.format((float) onLineSign / 2);
        return onlineRate;
    }


    /**
     * 5: 早高峰 6：晚高峰  6：平峰期 8：夜巡
     *
     * @param battalion 大队
     * @return
     * @throws Exception
     */
    @Override
    public List<HashMap> theDaySum(String battalion) {

        //当班在线累计警力
        Section section = sectionMapper.selectOne(Wrappers.<Section>lambdaQuery()
                .eq(Section::getSectionName, battalion));
        Integer id = null;
        if (section != null) {
            if (section.getSectionPid() == 74) {
                id = section.getSysSectionId();
            }
            if (section.getSectionPid() == 74 && !section.getSectionName().contains("支队")) {
                id = null;
                battalion = null;
            }
            if (section.getSectionPid() != 74) {
                id = section.getSectionPid();
            }

        }
        List<Map<String, Object>> police = signMapper.accumulative("民警", "1", id);
        List<Map<String, Object>> auxiliary = signMapper.accumulative("辅警", "1", id);


        String dayTime = dateFormat.format(new Date());

        List<HashMap> daySumList = new ArrayList<>();
        //日常。。。。。。。
        HashMap<String, Object> gdMap = new HashMap<>();
        //判断时间是什么时间段
        Calendar cal = Calendar.getInstance();
        int month = cal.get(Calendar.MONTH) + 1;
        List<Gatecard> gatecardByShifop = new ArrayList<>();
        //夏季
        if (month == 5 || month == 6 || month == 7 || month == 8 || month == 9) {
            gatecardByShifop = gatecardMapper.findGatecardByShifop(1, null, 2);
        } else { //冬季出勤
            //冬季勤务模式
            gatecardByShifop = gatecardMapper.findGatecardByShifop(2, null, 2);
        }
        //高峰期
        //早高峰出勤时间
        String morningPeakStart = null;
        String morningPeakEnd = null;
        //晚高峰出勤时间
        String eveningPeakStart = null;
        String eveningPeakEnd = null;
        //夜巡出勤
        String nightTourStart = null;
        String nightTourEnd = null;

        for (Gatecard gatecard : gatecardByShifop) {
            if (gatecard.getShiftop() == 5) {
                morningPeakStart = gatecard.getStartTime();
                morningPeakEnd = gatecard.getEndTime();
            }
            if (gatecard.getShiftop() == 6) {
                eveningPeakStart = gatecard.getStartTime();
                eveningPeakEnd = gatecard.getEndTime();
            }
            if (gatecard.getShiftop() == 8) {
                nightTourStart = gatecard.getStartTime();
                nightTourEnd = gatecard.getEndTime();
            }

        }


        Date date = new Date();
        /**
         * 早高峰
         */
        if (isEffectiveDate(date, DateUtil.parse(dayTime + " " + morningPeakStart), DateUtil.parse(dayTime + " " + morningPeakEnd)) || isEffectiveDate(date, DateUtil.parse(dayTime + " " + eveningPeakStart), DateUtil.parse(dayTime + " " + eveningPeakEnd))) {
            //日常勤务民警在线警力
            List<Map> onLineSign = signMapper.findOnLineStrength(null, null, battalion, "民警");
            List<Map> onLineSigns = signMapper.findOnLineStrength(null, null, battalion, "辅警");

            gdMap.put("type", "日常勤务");
            if (isEffectiveDate(date, DateUtil.parse(dayTime + " " + morningPeakStart), DateUtil.parse(dayTime + " " + morningPeakEnd))) {
                gdMap.put("time", "早高峰07:30-08:30");
            } else {
                gdMap.put("time", "晚高峰17:30-18:30");
            }
            gdMap.put("gfYDsum", police.size());
            gdMap.put("pfYDsum", auxiliary.size());

            gdMap.put("gfSDsum", onLineSign.size());
            gdMap.put("pfSDsum", onLineSigns.size());
            daySumList.add(gdMap);
            return daySumList;
        } else if (date.after(DateUtil.parse(nightTourStart)) || date.before(DateUtil.parse(nightTourEnd))) { //夜巡
            //日常勤务民警在线警力
            List<Map> onLineSign = signMapper.findOnLineStrength(null, null, battalion, "民警");
            List<Map> onLineSigns = signMapper.findOnLineStrength(null, null, battalion, "辅警");

            gdMap.put("type", "日常勤务");
            gdMap.put("time", "夜巡20:00-次日07:30");
            //累计签到
            gdMap.put("gfYDsum", police.size());
            //当班在线
            gdMap.put("gfSDsum", onLineSign.size());
            gdMap.put("pfYDsum", auxiliary.size());
            gdMap.put("pfSDsum", onLineSigns.size());
            daySumList.add(gdMap);
            return daySumList;
        } else { //平峰期
            /**
             *          * 日常勤务平峰期=（【高速大队（郑少+西南）除去事故中队和领导外全部民警人数的三分之一】
             *          +【（机动+网格+固定+铁骑）的民警人数一半】*//*
             */
            //日常勤务民警在线警力
            List<Map> onLineSign = signMapper.findOnLineStrength(null, null, battalion, "民警");
            List<Map> onLineSigns = signMapper.findOnLineStrength(null, null, battalion, "辅警");

            gdMap.put("type", "日常勤务");
            gdMap.put("time", "平峰期08:30-17:30");
            gdMap.put("gfYDsum", police.size());
            gdMap.put("gfSDsum", onLineSign.size());
            gdMap.put("pfYDsum", auxiliary.size());
            gdMap.put("pfSDsum", onLineSigns.size());
            daySumList.add(gdMap);
            return daySumList;
        }


    }


    @Override
    public Map<String, Object> typeSum(String battalion) {

        //根据大队查询在线人员
        //岗位
        List<Map<String, Object>> allStation = dutyModelMapper.findDutyModeAll();
        for (int i = 0; i < allStation.size(); i++) {
            if ("特勤".equals(allStation.get(i).get("postName").toString())) {
                allStation.remove(i);
                i--;
            }
            //民警在线警力数
            List<Map<String, Object>> onLineSign = signMapper.findOnLinePeople(allStation.get(i).get("postCode").toString(), battalion);
            allStation.get(i).put("SDnum", onLineSign.size());
        }

        //特殊勤务
        List<Map<String, Object>> sptypes = sptypeMapper.selectMaps(Wrappers.<Sptype>lambdaQuery().ne(Sptype::getYxzt, 0));
        for (Map sptype : sptypes) {
            List<Map<String, Object>> lx = xlevelserviceMapper.findOnLinePtrengthPid(sptype.get("id").toString(), battalion);
            sptype.put("name", sptype.get("ssname"));
            sptype.put("SDnum", lx.size());
            sptype.remove("ssname");
        }

        List<Map> maps = treeUtil.buildChildTree(sptypes);
        Map<String, Object> map = new HashMap<>();
        map.put("routineWork", allStation);
        map.put("specia", maps);
        List<Map<String, Object>> mapList = signMapper.OnlineStaff(battalion);
        map.put("policeStrength", mapList.size());

        return map;
    }

    @Override
    public List<Map<String, Object>> onLinePeople(Integer id) {
        //去当天数据
        String startTime = DataTime.getStartTheDay();
        String endTime = DataTime.getEndDate();
        //在线大队
        List<Map<String, Object>> onLineSection = sectionMapper.findOnLineSection(id);
        for (Map<String, Object> map : onLineSection) {
            long start = System.currentTimeMillis();
            String sectionName = map.get("sectionName").toString();
            Integer id1 = Integer.valueOf(map.get("id").toString());
            //在线人数
            List<Map> mapList = signMapper.OnlineSigns(sectionName);
            map.put("policeStrength", mapList.size());
            long end = System.currentTimeMillis();
            log.debug("在线人数执行时间{}", end - start);
//            //信息上报
//            int problemReport = problemMapper.findProblemReport(id1, startTime, endTime, null);
//            map.put("problemReport", problemReport);
//            //今日执法
//            Integer integer = illegalDataMapper.selectCount(Wrappers.<IllegalData>lambdaQuery()
//                    .like(org.apache.commons.lang3.StringUtils.isNotEmpty(sectionName), IllegalData::getBattalion, sectionName)
//                    .between(IllegalData::getWfsj, startTime, endTime));
//            map.put("enforce", integer);
//
//            //接处警数量
//            Section section = sectionMapper.selectByPrimaryKey(id1);
//            Integer JieChuJing = policeDataMapper.selectCount(Wrappers.<PoliceData>lambdaQuery()
//                    .eq(org.apache.commons.lang.StringUtils.isNotEmpty(sectionName), PoliceData::getJjdw, section.getSectionTel())
//                    .between(PoliceData::getJjsj01, startTime, endTime));
//
//            map.put("JieChuJing", JieChuJing);

            start = System.currentTimeMillis();
            //在线警车
            List<Map<String, Object>> vehicle = equipageMapper.findFacilityLocaltion(sectionName, "警车");
            map.put("vehicle", vehicle.size());
            //在线数字电台
            List<Map<String, Object>> digitalRadio = equipageMapper.findFacilityLocaltion(sectionName, "数字电台");
            map.put("digitalRadio", digitalRadio.size());
            //在线5G执法记录仪
            List<Map<String, Object>> recorder = equipageMapper.findFacilityLocaltion(sectionName, "执法记录仪");
            map.put("recorder", recorder.size());
            end = System.currentTimeMillis();
            log.debug("在线设备执行时间{}", end - start);

            start = System.currentTimeMillis();
            //累计签到人次
            List<Sign> signs = signMapper.selectList(Wrappers.<Sign>lambdaQuery()
                    .like(org.apache.commons.lang.StringUtils.isNotEmpty(sectionName), Sign::getSectionname, sectionName)
                    .between(Sign::getSignintime, startTime, endTime)
                    .isNotNull(Sign::getShiftop)
                    .groupBy(Sign::getShiftop, Sign::getWarningsignal));
            map.put("cumulativeSign", signs.size());
            end = System.currentTimeMillis();
            log.debug("累计签到人次执行时间{}", end - start);
        }
        return onLineSection;
    }

    //按时间段统计日间各个岗位应到实到人
    @Override
    public List<Map> typeSumByTime(String battalion) {
        //根据大队查询岗位类类型
        List<Map> stationBySection = xareaMapper.findStationBySection(battalion);
        return stationBySection;
    }


    /**
     * 日常勤务统计
     *
     * @param battalion
     * @return
     * @throws Exception
     */
    @Override
    public List<Map> countZD(String battalion) {
        // 创建一个数值格式化对象
        NumberFormat numberFormat = NumberFormat.getInstance();
        // 设置精确到小数点后2位
        numberFormat.setMaximumFractionDigits(2);
        //判断时间，高峰期、平峰期、夜巡
        //高峰期
        if ((DateUtil.parse(DateUtil.now()).after(SignTime.getStartDate(MORING))) && DateUtil.parse(DateUtil.now()).before(SignTime.getEndDate(MORING)) || (DateUtil.parse(DateUtil.now()).after(SignTime.getStartDate(EVENINGPEAKNOTSUMMER)) && DateUtil.parse(DateUtil.now()).before(SignTime.getEndDate(EVENINGPEAKNOTSUMMER)))) {
            //大队
            List<Map> sectionByBattation = sectionMapper.findSectionByBattation(battalion);
            for (Map map : sectionByBattation) {
                //查询该大队应有部署警力
                List<Map> staffByStation = staffMapper.findStaffByStation(Integer.valueOf(map.get("sectionDid").toString()), null, "高峰岗", "民警");
                //查询该大队在线警力
                List<Map> mapList = signMapper.OnLineInNumBymode(Integer.valueOf(map.get("sectionDid").toString()));
                map.put("ddYDnum", staffByStation.size());
                map.put("ddSDnum", mapList.size());

                //中队
                List<Map> sectionDid = sectionMapper.findSectionBydetachment(map.get("sectionDid").toString());
                for (Map map1 : sectionDid) {
                    //查询该中队应有部署警力
                    List<Map> staffByStation1 = staffMapper.findStaffByStation(null, Integer.valueOf(map1.get("sectionZid").toString()), "高峰岗", "民警");
                    //查询该中队在线民警
                    List<Map> mapList1 = signMapper.OnLineByLochus(Integer.valueOf(map1.get("sectionZid").toString()));
                    map1.put("YDnum", staffByStation1.size());
                    map1.put("SDnum", mapList1.size());
                    if (mapList1.size() == 0) {
                        map1.put("gfZXL", 0);

                    } else if (mapList1.size() > staffByStation1.size()) {
                        map1.put("gfZXL", 100);
                    } else {
                        map1.put("gfZXL", numberFormat.format((float) mapList1.size() / (float) staffByStation1.size() * 100));
                    }

                }
                map.put("zdCount", sectionDid);
            }
            return sectionByBattation;
            //夜巡
        } else if (DateUtil.parse(DateUtil.now()).after(SignTime.getStartDate(NIGHTWORK)) && DateUtil.parse(DateUtil.now()).before(SignTime.getEndDate(NIGHTWORK))) {
            //大队
            List<Map> sectionByBattation = sectionMapper.findSectionByBattation(battalion);
            for (Map map : sectionByBattation) {
                //查询该大队应有部署警力
                List<Map> staffByStation = staffMapper.findStaffByStation(Integer.valueOf(map.get("sectionDid").toString()), null, "夜巡", "民警");
                //查询该大队在线警力
                List<Map> mapList = signMapper.OnLineInNumBymode(Integer.valueOf(map.get("sectionDid").toString()));
                map.put("ddYDnum", staffByStation.size());
                map.put("ddSDnum", mapList.size());

                //中队
                List<Map> sectionDid = sectionMapper.findSectionBydetachment(map.get("sectionDid").toString());
                for (Map map1 : sectionDid) {
                    //查询该中队应有部署警力
                    List<Map> staffByStation1 = staffMapper.findStaffByStation(null, Integer.valueOf(map1.get("sectionZid").toString()), "夜巡", "民警");
                    //查询该中队在线民警
                    List<Map> mapList1 = signMapper.OnLineByLochusBymode(Integer.valueOf(map1.get("sectionZid").toString()));
                    map1.put("YDnum", staffByStation1.size());
                    map1.put("SDnum", mapList1.size());
                    if (mapList1.size() == 0) {
                        map1.put("gfZXL", 0);

                    } else if (mapList1.size() > staffByStation1.size()) {
                        map1.put("gfZXL", 100);
                    } else {
                        map1.put("gfZXL", numberFormat.format((float) mapList1.size() / (float) staffByStation1.size() * 100));
                    }

                }
                map.put("zdCount", sectionDid);
            }
            return sectionByBattation;
        } else { //平峰期
            //大队
            List<Map> sectionByBattation = sectionMapper.findSectionByBattation(battalion);
            for (Map map : sectionByBattation) {
                //查询该大队应有部署警力
                List<Map> staffByStation = staffMapper.findStaffByFlat(Integer.valueOf(map.get("sectionDid").toString()), null, "民警");
                //查询该大队在线警力
                List<Map> mapList = signMapper.OnLineInNumBymode(Integer.valueOf(map.get("sectionDid").toString()));
                map.put("ddYDnum", staffByStation.size());
                map.put("ddSDnum", mapList.size());

                //中队
                System.out.println(map.get("sectionDid").toString());
                List<Map> sectionDid = sectionMapper.findSectionBydetachment(map.get("sectionDid").toString());
                for (Map map1 : sectionDid) {
                    //查询该中队应有部署警力
                    int staffByStation1 = staffMapper.findStaffByFlat(null, Integer.valueOf(map1.get("sectionZid").toString()), "民警").size();
                    //查询该中队在线民警
                    List<Map> mapList1 = signMapper.OnLineByLochusBymode(Integer.valueOf(map1.get("sectionZid").toString()));
                    map1.put("YDnum", staffByStation1);
                    map1.put("SDnum", mapList1.size());
                    if (mapList1.size() == 0) {
                        map1.put("gfZXL", 0);

                    } else if (mapList1.size() > staffByStation1) {
                        map1.put("gfZXL", 100);
                    } else {
                        map1.put("gfZXL", numberFormat.format((float) mapList1.size() / (float) staffByStation1 * 100));
                    }

                }
                map.put("zdCount", sectionDid);
            }
            return sectionByBattation;
        }

    }

    @Override
    public List<Map> yXtypeSum(String battalion) {
        //夜间岗位
        List<Map> stationByNight = xareaMapper.findStationByNight(battalion);
        Xareas xareas = new Xareas();
        for (Map map : stationByNight) {
            //查询部署警力
            xareas.setStaffType("民警")
                    .setStation(map.get("name").toString())
                    .setSectionDid(Integer.valueOf(map.get("sectionDid").toString()));
            int policeStrength = xareaMapper.findPoliceStrength(xareas);
            map.put("YDnum", policeStrength);
        }
        return stationByNight;


    }


    /**
     * @param nowTime   当前时间
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @author sunran   判断当前时间在时间区间内
     */
    static boolean isEffectiveDate(Date nowTime, Date startTime, Date endTime) {
        if (nowTime.getTime() == startTime.getTime()
                || nowTime.getTime() == endTime.getTime()) {
            return true;
        }

        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);
        Calendar begin = Calendar.getInstance();
        begin.setTime(startTime);

        Calendar end = Calendar.getInstance();
        end.setTime(endTime);

        if (date.after(begin) && date.before(end)) {
            return true;
        } else {
            return false;
        }
    }

    //去坐标点
    private Double[] convertGps(List<Map<String, Object>> nowGps) {
        String[] coordinate = nowGps.get(0).get("coordinate").toString().split(",");
        int len = coordinate.length;
        if (len < 2) {
            return null;
        }

        Double[] gps = new Double[2];

        gps[0] = Double.parseDouble(coordinate[len - 2]);
        gps[1] = Double.parseDouble(coordinate[len - 1]);

        return gps;
    }

    @Override
    public List<StationData> findNowByGps(double[] lon, double[] lat, Integer sectionid) {
        List<String> stationName = Arrays.asList("固定岗", "高峰岗", "重点机关岗", "铁骑", "网格", "夜巡", "高速岗", "快速岗", "机动岗", "特勤岗");
        List<StationData> stationDataList = new ArrayList<>();
        stationName.forEach(name -> stationDataList.add(new StationData().setGangwei(name)));

        if (lon != null && lat != null) {
            //根据部门id查询在线警力
            List<HashMap<String, Object>> onlinePersonnel = signMapper.OnlinePersonnel(sectionid);
            if (onlinePersonnel.size() > 0) {
                for (HashMap<String, Object> online : onlinePersonnel) {
                    //人员id
                    int nowId = Integer.parseInt(online.get("id").toString());
                    //System.out.println("人员id：" + nowId);
                    List<Map<String, Object>> nowGps = locationMapper.findLocationById(nowId);
                    List<Map<String, Object>> mapList = signMapper.SignInNumByStaff(nowId);
                    //合并
                    List<Map<String, Object>> merge = DistanceUtil.merge(nowGps, mapList);

                    if (nowGps != null && merge != null) {
                        double longitude = Double.parseDouble(merge.get(0).get("longitude").toString());
                        double latitude = Double.parseDouble(merge.get(0).get("latitude").toString());
                        if (!"".equals(longitude)) {
                            boolean result = isInPolygon(longitude, latitude, lon, lat);
                            if (result) {
                                HashMap<String, Object> mappedMovies = new HashMap<>();
                                for (int i = 0; i < merge.size(); i++) {
                                    merge.get(i).put("gpsx", longitude);
                                    merge.get(i).put("gpsy", latitude);
                                    mappedMovies.putAll(merge.get(i));
                                }

                                String station = online.get("station").toString().split("-")[0];
                                String comment = online.get("comment").toString();
                                if (stationName.contains(station)) {
                                    stationDataList.stream().filter(o -> o.getGangwei().equals(station)).findFirst().ifPresent(stationData -> stationData.addData(mappedMovies));
                                } else if ("2".equals(comment)) {
                                    stationDataList.stream().filter(o -> o.getGangwei().equals("特勤岗")).findFirst().ifPresent(stationData -> stationData.addData(mappedMovies));
                                }
                            }
                        }
                    }
                }
            }
        }

        return stationDataList;

    }


    //根据大队名称查询在线人GPS
    @Override
    public List<HashMap> findNowStaffBySection(String time, String battalion, Integer type) {
        List<HashMap> staffBySectionList = new ArrayList<>();

        if (type == 1) {
            //高峰在线人ID
            List<Integer> gfList = patrolrecordMapper.findGFGPS(time, "高峰岗", battalion);
            for (Integer gfId : gfList) {
                HashMap<String, Object> gfStaffGps = patrolrecordMapper.findStaffGps(time, gfId);
                staffBySectionList.add(gfStaffGps);
            }

            //日常在线人ID
            List<Integer> rcList = patrolrecordMapper.findRcGPS(time, battalion);
            for (Integer rcId : rcList) {
                HashMap<String, Object> rcStaffGps = patrolrecordMapper.findStaffGps(time, rcId);
                staffBySectionList.add(rcStaffGps);
            }
        } else if (type == 2) {
            //日常在线人ID
            List<Integer> rcList = patrolrecordMapper.findRcGPS(time, battalion);
            for (Integer rcId : rcList) {
                HashMap<String, Object> rcStaffGps = patrolrecordMapper.findStaffGps(time, rcId);
                staffBySectionList.add(rcStaffGps);
            }
        } else if (type == 3) {
            //夜巡在线人ID
            List<Integer> yxList = patrolrecordMapper.findYXGPS(time, battalion);
            for (Integer yxId : yxList) {
                HashMap<String, Object> yxStaffGps = patrolrecordMapper.findStaffGps(time, yxId);
                staffBySectionList.add(yxStaffGps);
            }
        }

        return staffBySectionList;
    }

    //统计各大队在线、应到人数
    @Override
    public HashMap findStaffSum(String time, String battalion, Integer type) {
        HashMap staffSumMap = new HashMap();

        //高峰应到数
        List<HashMap> gfPeoples = xareaMapper.countYDSum("高峰岗", battalion, null);
        //网格+高速+铁骑+其他
        List<HashMap> rcPeoples = xareaMapper.countRcYDsumC2(battalion);
        //固定+重点
        List<HashMap> rcPeoples1 = xareaMapper.countRcYDsum(battalion);
        //夜巡
        List<HashMap> yxPeoples = xareaMapper.countYxSum("3", battalion, null);

        int gfYDSum = (gfPeoples.size()) + (rcPeoples.size()) + (rcPeoples1.size());
        int rcYDSum = (rcPeoples.size()) + (rcPeoples1.size());
        int yxYDSum = yxPeoples.size();

        int gdSD = signMapper.countByrwmc("固定", battalion, "民警", null);
        int gfSD = signMapper.countByrwmc("高峰", battalion, "民警", null);
        int tqSD = signMapper.countByrwmc("铁骑", battalion, "民警", null);
        //int wgSD = signMapper.countByrwmc("网格", battalion, "民警", null);
        int zdSD = signMapper.countByrwmc("重点", battalion, "民警", null);//重点
        //int gsSD = signMapper.countByrwmc("高速", battalion, "民警", null);
        //int ksSD = signMapper.countByrwmc("快速", battalion, "民警", null);
        int jdSD = signMapper.countByrwmc("机动", battalion, "民警", null);
        int yxSD = signMapper.countByrwmc("夜巡", battalion, "民警", null);


        //高峰岗=高峰岗+固定岗+机动岗+铁骑+重点机关岗
        // 平峰期=快速+机动+网格+固定+铁骑
        int gfSDSum = gfSD + gdSD + jdSD + tqSD + zdSD;
        int rcSDSum = gfSD + gdSD + jdSD + tqSD + zdSD;

        if (type == 1) {

            staffSumMap.put("SDsum", gfSDSum);
            staffSumMap.put("YDsum", gfYDSum);

        } else if (type == 2) {

            staffSumMap.put("SDsum", rcSDSum);
            staffSumMap.put("YDsum", rcYDSum);

        } else if (type == 3) {

            staffSumMap.put("SDsum", yxSD);
            staffSumMap.put("YDsum", yxYDSum);

        }

        return staffSumMap;
    }

    /**
     * 判断是否在多边形区域内
     *
     * @param pointLon 要判断的点的纵坐标
     * @param pointLat 要判断的点的横坐标
     * @param lon      区域各顶点的纵坐标数组
     * @param lat      区域各顶点的横坐标数组
     * @return
     */
    public static boolean isInPolygon(double pointLon, double pointLat, double[] lon,
                                      double[] lat) {
        // 将要判断的横纵坐标组成一个点
        Point2D.Double point = new Point2D.Double(pointLon, pointLat);
        // 将区域各顶点的横纵坐标放到一个点集合里面EARTH_RADIUS
        List<Point2D.Double> pointList = new ArrayList<Point2D.Double>();
        double polygonPoint_x = 0.0, polygonPoint_y = 0.0;
        for (int i = 0; i < lon.length; i++) {
            polygonPoint_x = lon[i];
            polygonPoint_y = lat[i];
            Point2D.Double polygonPoint = new Point2D.Double(polygonPoint_x, polygonPoint_y);
            pointList.add(polygonPoint);
        }
        return check(point, pointList);
    }

    /**
     * 一个点是否在多边形内
     *
     * @param point   要判断的点的横纵坐标
     * @param polygon 组成的顶点坐标集合
     * @return
     */
    private static boolean check(Point2D.Double point, List<Point2D.Double> polygon) {
        java.awt.geom.GeneralPath peneralPath = new java.awt.geom.GeneralPath();

        Point2D.Double first = polygon.get(0);
        // 通过移动到指定坐标（以双精度指定），将一个点添加到路径中
        peneralPath.moveTo(first.x, first.y);
        polygon.remove(0);
        for (Point2D.Double d : polygon) {
            // 通过绘制一条从当前坐标到新指定坐标（以双精度指定）的直线，将一个点添加到路径中。
            peneralPath.lineTo(d.x, d.y);
        }
        // 将几何多边形封闭
        peneralPath.lineTo(first.x, first.y);
        peneralPath.closePath();
        // 测试指定的 Point2D 是否在 Shape 的边界内。
        return peneralPath.contains(point);
    }

    @Override
    public List<StationData> findCircleByGps(double circleX, double circleY, double r, Integer sectionid) {

        List<String> stationName = Arrays.asList("固定岗", "高峰岗", "重点机关岗", "铁骑", "网格", "夜巡", "高速岗", "快速岗", "机动岗", "特勤岗");
        List<StationData> stationDataList = new ArrayList<>();
        stationName.forEach(name -> stationDataList.add(new StationData().setGangwei(name)));

        List<HashMap<String, Object>> onlinePersonnel = signMapper.OnlinePersonnel(sectionid);
        if (onlinePersonnel.size() > 0) {
            for (HashMap<String, Object> online : onlinePersonnel) {
                int nowId = Integer.parseInt(online.get("id").toString());
                List<Map<String, Object>> nowGps = locationMapper.findLocationById(nowId);
                List<Map<String, Object>> mapList = signMapper.SignInNumByStaff(nowId);
                //合并
                List<Map<String, Object>> merge = DistanceUtil.merge(nowGps, mapList);
                if (merge != null) {
                    double longitude1 = Double.parseDouble(merge.get(0).get("longitude").toString());
                    double latitude1 = Double.parseDouble(merge.get(0).get("latitude").toString());
                    if (!"".equals(longitude1)) {
                        boolean result = DistanceUtil.isInCircle(longitude1, latitude1, circleX, circleY, r);
                        HashMap<String, Object> mappedMovies = new HashMap<>();
                        if (result) {

                            for (int i = 0; i < merge.size(); i++) {
                                merge.get(i).put("gpsx", longitude1);
                                merge.get(i).put("gpsy", latitude1);
                                mappedMovies.putAll(merge.get(i));
                            }
                            String station = online.get("station").toString().split("-")[0];
                            String comment = online.get("comment").toString();
                            if (stationName.contains(station)) {
                                stationDataList.stream().filter(o -> o.getGangwei().equals(station)).findFirst().ifPresent(stationData -> stationData.addData(mappedMovies));
                            } else if ("2".equals(comment)) {
                                stationDataList.stream().filter(o -> o.getGangwei().equals("特勤岗")).findFirst().ifPresent(stationData -> stationData.addData(mappedMovies));
                            }
                        }
                    }
                }
            }
        }

        return stationDataList;

    }

    @Override
    public ResultBean selectinfoByid(Integer id) {
        HashMap patrolrecord = patrolrecordMapper.selectinfoByid(id);
        if (patrolrecord != null) {
            return ResultUtil.setOK("success", patrolrecord);
        }
        return ResultUtil.setError(SystemCon.RERROR1, "error", null);
    }


    //热力图统计
    @Override
    public List<HashMap> heatMap(String battalion) {
        //查询所有面的坐标（按大队查询）
        List<HashMap> typeGPSList = patrolrecordMapper.findByType(battalion);
        //List<HashMap> typeGPSList = gisLocationMapper.selectGis(battalion);
        List<HashMap> resultList = new ArrayList<>();
        List<List<Map<String, Object>>> nowGpsList = new ArrayList<>();
        //查询所有当前签到在线的警员（按大队查询）
        List<Integer> nowIds = signMapper.selectNowId(battalion);
        for (Integer nowId : nowIds) {
            List<Map<String, Object>> nowGps = patrolrecordMapper.findNowGps(nowId);
            nowGpsList.add(nowGps);
        }
        for (HashMap map : typeGPSList) {
            String gps = map.get("gps").toString();
            String[] split = gps.split(",");
            int num = 0;

            List<String> lonList = new ArrayList<>();//经度集合
            List<String> latList = new ArrayList<>();//维度集合

            for (int i = 1; i <= split.length; i++) {
                String s = split[i - 1];
                if (i % 2 == 0) {
                    //偶数
                    latList.add(s);
                } else {
                    lonList.add(s);
                }
            }

            double[] lonArr = new double[lonList.size()];
            double[] latArr = new double[latList.size()];
            for (int j = 0; j < lonList.size(); j++) {
                Double aa = Double.parseDouble(lonList.get(j));
                lonArr[j] = aa;
            }

            for (int k = 0; k < latList.size(); k++) {
                Double aa = Double.parseDouble(latList.get(k));
                latArr[k] = aa;
            }
            if (nowIds.size() > 0) {
                for (int l = 0; l < nowGpsList.size(); l++) {
                    if (nowGpsList.get(l) != null) {
                        Double[] coordinate = convertGps(nowGpsList.get(l));
                        boolean result = isInPolygon(coordinate[0], coordinate[1], lonArr, latArr);
                        if (result) {
                            num++;
                            nowGpsList.remove(l);
                        }
                    }

                }
            }
            String centre = map.get("centre").toString();
            HashMap<String, Object> resultMap = new HashMap<>();
            resultMap.put("centre", centre);
            resultMap.put("num", num);

            resultList.add(resultMap);
        }

        return resultList;
    }

    //热力图统计
    @Override
    public List<HashMap> heatMapYD(String battalion) {
        //查询网格
        List<HashMap> typeGPSList = patrolrecordMapper.findByType(battalion);

        List<HashMap> dianList = patrolrecordMapper.findTypeGps("点", battalion);
        List<HashMap> xianList = patrolrecordMapper.findTypeGps("线", battalion);
        List<HashMap> mianList = patrolrecordMapper.findTypeGps("面", battalion);

        List<HashMap> resultList = new ArrayList<>();

        int sum = 0;

        for (HashMap map : typeGPSList) {
            String gps = map.get("gps").toString();
            String[] split = gps.split(",");
            int num = 0;

            List<String> lonList = new ArrayList<>();//经度集合
            List<String> latList = new ArrayList<>();//维度集合

            for (int i = 1; i <= split.length; i++) {
                String s = split[i - 1];
                if (i % 2 == 0) {
                    //偶数
                    latList.add(s);
                } else {
                    lonList.add(s);
                }
            }

            double[] lonArr = new double[lonList.size()];
            double[] latArr = new double[latList.size()];
            for (int j = 0; j < lonList.size(); j++) {
                Double aa = Double.parseDouble(lonList.get(j));
                lonArr[j] = aa;
            }

            for (int k = 0; k < latList.size(); k++) {
                Double aa = Double.parseDouble(latList.get(k));
                latArr[k] = aa;
            }

            //点
            for (int a = 0; a < dianList.size(); a++) {
                String gps_x = dianList.get(a).get("gps").toString().split(",")[0];
                String gps_y = dianList.get(a).get("gps").toString().split(",")[1];

                Double x = Double.parseDouble(gps_x);
                Double y = Double.parseDouble(gps_y);

                boolean result = isInPolygon(x, y, lonArr, latArr);
                if (result) {
                    num++;
                    dianList.remove(a);
                }
            }

            //线
            for (int b = 0; b < xianList.size(); b++) {
                if (!StringUtils.isEmpty(xianList.get(b).get("centre"))) {
                    String gps_x = xianList.get(b).get("centre").toString().split(",")[0];
                    String gps_y = xianList.get(b).get("centre").toString().split(",")[1];

                    Double x = Double.parseDouble(gps_x);
                    Double y = Double.parseDouble(gps_y);
                    boolean result = isInPolygon(x, y, lonArr, latArr);
                    if (result) {
                        num++;
                        xianList.remove(b);
                    }
                } else {
                    String gps_x = xianList.get(b).get("gps").toString().split(",")[0];
                    String gps_y = xianList.get(b).get("gps").toString().split(",")[1];

                    Double x = Double.parseDouble(gps_x);
                    Double y = Double.parseDouble(gps_y);

                    boolean result = isInPolygon(x, y, lonArr, latArr);
                    if (result) {
                        num++;
                        xianList.remove(b);
                    }
                }

            }

            //面
            for (int c = 0; c < mianList.size(); c++) {
                if (!StringUtils.isEmpty(mianList.get(c).get("centre"))) {
                    String gps_x = mianList.get(c).get("centre").toString().split(",")[0];
                    String gps_y = mianList.get(c).get("centre").toString().split(",")[1];

                    Double x = Double.parseDouble(gps_x);
                    Double y = Double.parseDouble(gps_y);

                    boolean result = isInPolygon(x, y, lonArr, latArr);
                    if (result) {
                        num++;
                        mianList.remove(c);
                    }
                } else {
                    String gps_x = mianList.get(c).get("gps").toString().split(",")[0];
                    String gps_y = mianList.get(c).get("gps").toString().split(",")[1];

                    Double x = Double.parseDouble(gps_x);
                    Double y = Double.parseDouble(gps_y);

                    boolean result = isInPolygon(x, y, lonArr, latArr);
                    if (result) {
                        num++;
                        mianList.remove(c);
                    }
                }

            }


            String centre = map.get("centre").toString();
            HashMap<String, Object> resultMap = new HashMap<>();
            resultMap.put("centre", centre);

            resultMap.put("num", num);

            resultList.add(resultMap);

            sum += num;
        }
        return resultList;
    }

    @Override
    public String exportPatrolRecord(HttpServletResponse response, Integer staffid, String beginTime,
                                     String endTime, String staffnum) throws IOException {
        //登陆人信息
        Staff staff = staffMapper.selectByPrimaryKey(staffid);
        if (staff == null) {
            return null;
        }

        // 通过工具类创建writer
        ExcelWriter writer = ExcelUtil.getWriter(true);
        // 设置只导出有别名的字段
        writer.setOnlyAlias(true);
        List<Map> patrolrecord = patrolrecordMapper.findPatrolrecord(beginTime, endTime, staffnum);
        ArrayList<Map<String, Object>> rows = CollUtil.newArrayList();
        patrolrecord.forEach(map -> {
            String signnum1;
            if ("".equals(map.get("signnum")) || map.get("signnum").equals(null)) {
                signnum1 = "1";
            } else {
                signnum1 = map.get("signnum").toString();
            }

            double signnum = gpsMapper.findMileages(signnum1);
            List<Map> signByNum = signMapper.findSignByNum(signnum1);
            String job = "";
            for (Map map1 : signByNum) {
                job += map1.get("assignmentname") + "\n";
            }
            Map<String, Object> row1 = new LinkedHashMap<>();
            row1.put("警号", map.get("warningsignal"));
            row1.put("姓名", map.get("staffname"));
            row1.put("单位", map.get("sectionname"));
            row1.put("开始时间", map.get("patrolRecordBegintime"));
            row1.put("结束时间", map.get("patrolRecordEndtime"));
            row1.put("里程", signnum);
            row1.put("签到岗位", job);
            rows.add(row1);
        });
        String fileName = System.currentTimeMillis() + ".xlsx";
        // 合并单元格后的标题行，使用默认标题样式
        writer.merge(6, "巡查记录表");


        // 一次性写出内容，使用默认样式，强制输出标题
        writer.write(rows, true);
        writer.setRowHeight(-1, 38);
        writer.setColumnWidth(-1, 18);
        writer.setColumnWidth(6, 60);
        //设置某几行的对齐方式
        CellStyle style = writer.createCellStyle(0, rows.size() + 2);
        //下边框线颜色
        style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setHeader("Content-Disposition",
                "attachment;filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\"");
        ServletOutputStream out = response.getOutputStream();
        // 关闭writer，释放内存
        writer.flush(out, true);
        writer.close();
        IoUtil.close(out);

        return fileName;

    }

    /**
     * ===================================路长巡查列表整改==============================================================
     */

    @Override
    public PageInfo<Map> findPatrolrecordInfo(Patrol patrol) {
        PageHelper.startPage(patrol.getPageNum(), patrol.getPageSize());
        List<Map> patrolrecordInfo = patrolrecordMapper.findPatrolrecordInfo(patrol);
        PageInfo<Map> patrolrecord = new PageInfo<>(patrolrecordInfo);
        return patrolrecord;

    }

}

